<template>
  <div class="home">
    <input
      type="text"
      v-model="title"
      @keydown.up="up"
      @keydown.down="down"
      @keydown.enter="search"
    />
    <ul class="">
      <li
        v-for="(item, index) in $store.state.list"
        :key="index"
        @mouseenter="change(index)"
        :class="{ active: flag == index }"
      >
        {{ item.title }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      flag: -1,
      // flag的作用就是保存选择的是谁的下标
    };
  },
  methods: {
    change(index) {
      this.flag = index;
      this.title = this.$store.state.list[index].title;
    },
    //鼠标移入li的时候 把input v-model的title 变成vuex中对应下标的数据的title
    up() {
      this.flag--;
      if (this.flag < 0) {
        this.flag = this.$store.state.list.length - 1;
      }
      this.title = this.$store.state.list[this.flag].title;
    },
    // 键盘按下 up键的时候 当前显示的数据的下标减减 到了临界值 -1 变为最大下标
    // 把input v-model的title 变成vuex中对应下标的数据的title
    down() {
      this.flag++;
      if (this.flag > this.$store.state.list.length - 1) {
        this.flag = 0;
      }
      this.title = this.$store.state.list[this.flag].title;
    },
    // 键盘按下 down键的时候 当前显示的数据的下标++ 到了临界值  变为最小下标0
    // 把input v-model的title 变成vuex中对应下标的数据的title

    search() {
      this.$router.push({ path: "/result", query: { title: this.title } });
    },
  },
};
</script>
<style lang="scss">
.home {
  width: 500px;
  margin: 100px auto;
  input {
    width: 300px;
    height: 40px;
  }
  ul {
    border: 1px solid #ccc;
    li {
      height: 40px;
    }
    .active {
      background: #ccc;
    }
  }
}
</style>
